//
//  LumbaJackService.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/5/18.
//  Copyright © 2023 zwb. All rights reserved.
//

import UIKit
import CocoaLumberjack
class LumbaJackService: NSObject {
    static let shared = LumbaJackService()
     private override init() {}
    
  
    func addLoggers() {
        /// 添加控制台打印
//        DDLog.add(DDOSLogger.sharedInstance)
        
 ////        //修改Logs文件夹的位置
//        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
//        let logDirectory = path?.appendingPathComponent("Logs")
//        let fileLoggerManagerDefault = DDLogFileSub.init(logsDirectory: logDirectory)
//
//        let fileLogger = DDFileLogger.init(logFileManager: fileLoggerManagerDefault)
 
        let fileLogger = DDFileLogger(logFileManager: DDLogFileSub())
        //重用log文件，不要每次启动都创建新的log文件(默认值是NO)
        fileLogger.doNotReuseLogFiles = false;
        //log文件在1小时内有效，超过时间创建新log文件(默认值是24小时)
        fileLogger.rollingFrequency = 60*60*1;
        //禁用文件大小滚动
        fileLogger.maximumFileSize = 0;
        //最多保存1个log文件
        fileLogger.logFileManager.maximumNumberOfLogFiles = 1;
        //log文件夹最多保存10M
        fileLogger.logFileManager.logFilesDiskQuota = 1024*1024*10;
        // 设置日志格式
        fileLogger.logFormatter = self
        DDLog.add(fileLogger) // 添加文件日志
    }
}
/// 重写文件名
class DDLogFileSub: DDLogFileManagerDefault {
    
    override func isLogFile(withName fileName: String) -> Bool {
        let hasSuffix = fileName.hasSuffix(".log")
        return hasSuffix
    }
    
    override var newLogFileName: String{
        get{ self.creatNewLogFileName() }
        set{}
    }
    
    func creatNewLogFileName() -> String {

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM.dd HH"
        let timeStamp = dateFormatter.string(from: NSDate.init() as Date)

        let disPlayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") ?? "defaultlog"
        return "\(disPlayName).log"

    }
    
}
extension LumbaJackService:DDLogFormatter {

    func format(message logMessage: DDLogMessage) -> String? {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM-dd HH:mm:ss:SSS"
        let timeStamp = dateFormatter.string(from: NSDate.init() as Date)
        
        let formatLog = "\(timeStamp)->\(logMessage.function ?? "")->\(logMessage.message)";
        return formatLog;
    }

}
